<template>
  <div>
    <el-form :inline="true" :model="searchForm" width="30%">
      <el-form-item label="课程名">
        <el-input v-model="searchForm.courseName" placeholder="请输入课程名"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="info" @click="refreshCourses">刷新课程</el-button>
    <el-table :data="courses" style="width: 100%" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="courseId" label="课程ID" width="100"></el-table-column>
      <el-table-column prop="courseName" label="课程名称"></el-table-column>
      <el-table-column prop="courseCredit" label="学分"></el-table-column>
      <el-table-column prop="courseTime" label="学时"></el-table-column>
      <el-table-column prop="remark" label="备注"></el-table-column>
      <el-table-column label="操作" width="240">
        <template #default="scope">
          <el-button size="mini" @click="showStudentsDialog(scope.row)">选课</el-button>
          <el-button size="mini" @click="showEnrolledStudents(scope.row)">查看已选学生</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog title="选择学生" v-model="studentsDialogVisible" width="50%">
      <el-table :data="students" style="width: 100%" @selection-change="handleStudentSelectionChange">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="stuId" label="学生ID" width="100"></el-table-column>
        <el-table-column prop="stuName" label="姓名"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
      </el-table>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="studentsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="enrollSelectedStudents">确认选课</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="已选学生" v-model="enrolledStudentsDialogVisible" width="50%">
      <el-table :data="enrolledStudents" style="width: 100%">
        <el-table-column prop="stuId" label="学生ID" width="100"></el-table-column>
        <el-table-column prop="stuName" label="姓名"></el-table-column>
        <el-table-column prop="stuNumber" label="学号"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="sex" label="性别"></el-table-column>
        <el-table-column prop="age" label="年龄"></el-table-column>
        <el-table-column prop="phone" label="电话"></el-table-column>
        <el-table-column prop="remark" label="备注"></el-table-column>
        <el-table-column label="操作" width="180">
          <template #default="scope">
            <el-button size="mini" type="danger" @click="DeleteStudent(scope.row.stuId, scope.row.stuName)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template v-slot:footer>
        <span class="dialog-footer">
          <el-button @click="enrolledStudentsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import {ElMessageBox} from "element-plus";

export default {
  name: 'StudentCourseList',
  data() {
    return {
      courses: [],
      searchForm: {
        courseName: ''
      },
      selectedCourses: [], // 用于存储选中的课程
      students: [], // 存储学生数据
      studentsDialogVisible: false, // 控制显示学生列表的对话框
      selectedStudents: [], // 用于存储选中的学生
      enrolledStudents: [], // 存储已选该课程的学生数据
      enrolledStudentsDialogVisible: false, // 控制显示已选学生列表的对话框
    };
  },
  methods: {
    async fetchCourses(params) {
      try {
        const response = await axios.get(`${process.env.VUE_APP_API_BASE_URL}/courses/list`, { params });
        this.courses = response.data;
      } catch (error) {
        console.error('Failed to fetch courses:', error);
      }
    },
    onSearch() {
      this.fetchCourses({ courseName: this.searchForm.courseName });
    },
    resetForm() {
      this.searchForm.courseName = '';
      this.fetchCourses({});
    },
    refreshCourses() {
      this.fetchCourses();
    },
    async fetchStudents() {
      try {
        const response = await axios.get(`${process.env.VUE_APP_API_BASE_URL}/students/list`);
        this.students = response.data;
      } catch (error) {
        console.error('Failed to fetch students:', error);
      }
    },
    showStudentsDialog(course) {
      this.currentCourse = course;
      this.fetchStudents();
      this.studentsDialogVisible = true;
    },
    DeleteStudent(stuId, stuName) {
      ElMessageBox.confirm(
          `确定要删除学生 "${stuName}" 吗？`,
          '警告',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
      ).then(() => {
        this.deleteStudent(stuId);
      }).catch(() => {
        // 用户取消删除
      });
    },
    async deleteStudent(stuId) {
      // 发送 DELETE 请求来删除学生
      try {
        await axios.delete(`${process.env.VUE_APP_API_BASE_URL}/studentCourse/delete/${stuId}`);
        this.students = this.students.filter(student => student.stuId !== stuId);
        this.enrolledStudentsDialogVisible = false;
      } catch (error) {
        console.error('Failed to delete student:', error);
      }
    },
    enrollSelectedStudents() {
      if (this.selectedStudents.length === 0) {
        this.$message({
          message: '请选择至少一个学生',
          type: 'warning'
        });
        return;
      }
      const studentIds = this.selectedStudents.map(student => student.stuId);
      const data = {
        courseId: this.currentCourse.courseId,
        studentIds: studentIds
      };
      axios.post(`${process.env.VUE_APP_API_BASE_URL}/studentCourse/enrollStudents`, data)
          .then(() => {
            this.$message({
              message: '学生成功选课',
              type: 'success'
            });
            this.studentsDialogVisible = false;
          })
          .catch(error => {
            console.error('Failed to enroll students:', error);
            this.$message({
              message: '选课失败',
              type: 'error'
            });
          });
    },
    handleSelectionChange(selection) {
      this.selectedCourses = selection;
    },
    handleStudentSelectionChange(selection) {
      this.selectedStudents = selection;
    },
    async fetchEnrolledStudents(courseId) {
      try{
        const response =await axios.get(`${process.env.VUE_APP_API_BASE_URL}/studentCourse/enrolledStudents/${courseId}`)
        this.enrolledStudents = response.data;
        this.enrolledStudentsDialogVisible = true;
      }catch(error) {
        console.error('Failed to fetch enrolled students:', error);
        this.$message({
          message: '获取已选学生失败',
          type: 'error'
        });
      }
    },
    showEnrolledStudents(course) {
      this.fetchEnrolledStudents(course.courseId);
      this.enrolledStudentsDialogVisible = true;
    },
  },
  mounted() {
    this.fetchCourses(); // 页面加载时立即获取课程列表
  }
};
</script>

<style scoped>
.el-select {
  width: 100%; /* 确保下拉框宽度足够 */
}
</style> 